package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmMaterialService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.json.Json;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-13
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    private IWmNewsMaterialService wmMaterialService;

    @Autowired
    @Lazy    // 解决循环依赖问题
    private IAuditService auditService;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {

        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();

        if (dto.getStatus() != null) {

            // System.out.println("此时审核通过的号是"+dto.getStatus());

            query.eq(WmNews::getStatus, dto.getStatus());
        }
        if (!StringUtils.isEmpty(dto.getKeyword())) {

            query.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {

            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null) {

            query.gt(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            query.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }

        User user = MediaThreadLocalUtil.get();

        if (user == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        query.eq(WmNews::getUserId, user.getUserId());

        query.orderByDesc(WmNews::getPublishTime);

        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmNews> iPage = this.page(page, query);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());

        return result;
    }

    @Override
    @GlobalTransactional
    public ResponseResult submit(WmNewsDto dto) {

        User user = MediaThreadLocalUtil.get();

        if (user == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getId() != null) {

            deleteRelation(dto.getId());
        }
        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setUserId(user.getUserId());

        wmNews.setCreatedTime(new Date());

        if (dto.getStatus() != 0) {

            wmNews.setSubmitedTime(new Date());
        }

        wmNews.setImages(JSON.toJSONString(dto.getImages()));

        List<ImageDto> contentImages = getImagesFromContent(dto.getContent());

        if (dto.getType() == -1) {

            int size = contentImages.size();

            if (size <= 0) {

                wmNews.setType(0);
            } else if (size < 3) {

                wmNews.setType(1);

                ImageDto imageDto = contentImages.get(0);

                List<ImageDto> list = new ArrayList<>();

                list.add(imageDto);

                wmNews.setImages(JSON.toJSONString(list));
            } else {

                wmNews.setType(3);

                List<ImageDto> list = contentImages.subList(0, 3);

                wmNews.setImages(JSON.toJSONString(list));
            }
        }
        this.saveOrUpdate(wmNews);

        if (dto.getStatus() != 0) {

            List<ImageDto> coverImages = JSON.parseArray(wmNews.getImages(), ImageDto.class);

            saveRelation(coverImages, 1, wmNews.getId());
            // 关联内容中的图片
            saveRelation(contentImages, 0, wmNews.getId());

            System.out.println(Thread.currentThread().getName() + "调用自动审核服务");

            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        WmNews byId = this.getById(dto.getId());

        if (byId == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (byId.getStatus() != 9) {

            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        byId.setEnable(dto.getEnable() == 0 ? false : true);

        this.updateById(byId);

        kafkaTemplate.send(upDownTopic,byId.getArticleId().toString(),dto.getEnable()==1?"true":"false");

        return ResponseResult.okResult();
    }

    private void saveRelation(List<ImageDto> list, int i, Integer id) {

        int ord = 0;

        for (ImageDto imageDto : list) {

            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();

            wmNewsMaterial.setMaterialId(imageDto.getId());

            wmNewsMaterial.setNewsId(id);

            wmNewsMaterial.setOrd(ord);

            wmNewsMaterial.setType(i);

            wmMaterialService.save(wmNewsMaterial);
        }
    }

    private List<ImageDto> getImagesFromContent(String content) {

        List<ImageDto> imageDtos = new ArrayList<>();

        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);

        for (ContentDto contentDto : contentDtos) {

            if (contentDto.getType().equals("image")) {

                ImageDto imageDto = new ImageDto();

                imageDto.setId(contentDto.getId());

                imageDto.setUrl(contentDto.getValue());

                imageDtos.add(imageDto);
            }
        }
        return imageDtos;
    }


    private void deleteRelation(Integer id) {

        LambdaQueryWrapper<WmNewsMaterial> query = new LambdaQueryWrapper<>();

        query.eq(WmNewsMaterial::getNewsId, id);

        wmMaterialService.remove(query);
    }
}
